
import Flutter
import UIKit
import TXLoginoauthSDK

public class RuhunVerifyPlugin: NSObject, FlutterPlugin, UITextFieldDelegate {
    static var channel: FlutterMethodChannel!
    var textField : UITextField!
    public static func register(with registrar: FlutterPluginRegistrar) {
        channel = FlutterMethodChannel(name: "ruhun_verify", binaryMessenger: registrar.messenger())
        let instance = RuhunVerifyPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    var uiModel = TXLoginUIModel()

    let lvc = LoginViewController()

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

        switch call.method {

        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)

        case "initLoginWithId":

            let vc = UIApplication.shared.keyWindow?.rootViewController
            // 1. 将子视图控制器添加到父视图控制器
            lvc.uiModel = uiModel
            vc?.addChild(lvc)

            if let args = call.arguments as? Dictionary<String, Any?> {
                let initId = args["id"] as? String
                let timeout = args["timeout"] as? TimeInterval
                let appName = args["appName"] as? String ?? "入魂一番赏"

                TXLoginOauthSDK.initLogin(withId: initId ?? "")
                TXLoginOauthSDK.setTimeoutInterval(timeout ?? 5000)

                setUIModel(appName:appName)

                result(["appId":initId])
            }

        case "getSimInfo":
            let dict = TXLoginOauthSDK.getSimInfo()
            if let carrier = dict["carrier"] as? Int {
                lvc.carrier = carrier
            }
            result(dict)

        case "preLoginWithBack":
            TXLoginOauthSDK.preLogin { dict in
                result(dict)
            } fail: { error in
                result(error)
            }

        case "delectScrip":
            result(TXLoginOauthSDK.delectScrip())

        case "loginWithController":
            lvc.checkedP = false
            if let vc = UIApplication.shared.keyWindow?.rootViewController {
                TXLoginOauthSDK.login(with: vc, andUIModel:uiModel, successBlock: { [self] dict in
                    if(dict["loginResultCode"] as! String == "200087"){
                        print("拉起授权页面成功")
                        result(dict)
                    }else{
                        //获取到token返回给flutter（带上邀请码，如果有）
                        let vc = UIApplication.shared.keyWindow?.rootViewController
                        vc?.dismiss(animated: true)
                        uiModel.privacyState = false
                        var dict2 = dict
                        dict2["inviteCode"] = textField.text
                        RuhunVerifyPlugin.channel.invokeMethod("getToken", arguments: dict2)
                    }
                }, fail: { error in
                    result(error)
                })
            }

        case "closeAuthView":
            backClick()
            result(true)
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    func setUIModel(appName:String) {
        let SCREEN_RECT_WIDTH = UIScreen.main.bounds.size.width
        let SCREEN_RECT_HEIGHT = UIScreen.main.bounds.size.height
        let kBAR_HEIGHT = (UIScreen.main.bounds.size.height >= 812 ? 88.0: 64.0)

        /*状态栏设置*/
        uiModel.statusBarStyle = .default
        var link1 = "https://static.ichibankuji.cn/html/user_protocol.html";
        var link2 = "https://static.ichibankuji.cn/html/privacy_policy.html";
        if(appName == "入魂大集"){
            /**logo的图片设置*/
            uiModel.iconImage = UIImage(named: "logo_daji")!
            /**LOGO图片frame*/
            uiModel.logoFrame = CGRect(x: (SCREEN_RECT_WIDTH - 75) / 2, y: 130, width: 75, height: 75)
            link1 = "https://static.ichibankuji.cn/html/daji/user_protocol.html";
            link2 = "https://static.ichibankuji.cn/html/daji/privacy_policy.html";
        }else{
            /**logo的图片设置*/
            uiModel.iconImage = UIImage(named: "logo")!
            /**LOGO图片frame*/
            uiModel.logoFrame = CGRect(x: (SCREEN_RECT_WIDTH - 75) / 2, y: 130, width: 75, height: 66)
        }
        //LOGO图片是否隐藏,默认显示 NO
        uiModel.logoHidden = false

        /**手机号码相关设置*/
        uiModel.numberOffsetX = 0
        uiModel.numberTextAttributes = [.foregroundColor: UIColor.black, .font: UIFont.boldSystemFont(ofSize: 26)]
        uiModel.txMobliNumberOffsetY = SCREEN_RECT_HEIGHT - 250.0 as NSNumber

        /**品牌logo 相关属性*/
        uiModel.sloganTextColor = UIColor.black
        uiModel.brandLabelTextSize = UIFont.systemFont(ofSize: 11)
        uiModel.sloganHidden = false
        uiModel.sloganLabelOffsetY = SCREEN_RECT_HEIGHT - 275.0

        //背景
        uiModel.viewBackImg = UIImage.init(named: "login_bg")!

        //登录页面弹出动画
        uiModel.presentAnimated = true
        uiModel.presentType = .right

        //顶部view设置
        let topFrame = CGRectMake(0, 0,SCREEN_RECT_WIDTH, kBAR_HEIGHT)
        uiModel.customTopLoginView = setTopNavViewWithFrame(frame: topFrame)

        /*登录按钮透明*/
        uiModel.logBtnOffsetY = SCREEN_RECT_HEIGHT - 420
        uiModel.logBtnText = NSAttributedString.init(string: "")
        uiModel.logBtnHeight = 58
        uiModel.logBtnOriginLR = [30,30]
        uiModel.loginBtnImgs = [UIImage.init(named: "login_a")!,UIImage.init(named: "login_a")!,UIImage.init(named: "login_a")!]


        /*其他登录按钮*/
        let smsBtn = UIButton.init(frame: CGRectMake(28, SCREEN_RECT_HEIGHT - uiModel.logBtnOffsetY + 10, SCREEN_RECT_WIDTH - 56, 58))
        smsBtn.setImage(UIImage.init(named: "sms_login"), for: .normal)
        smsBtn.imageView?.contentMode = .scaleAspectFit
        smsBtn.addTarget(self, action: #selector(smsLogin), for: .touchUpInside)

        /*登录按钮*/
        let smsBtn2 = UIButton.init(frame: CGRectMake(28, SCREEN_RECT_HEIGHT - uiModel.logBtnOffsetY - 58, SCREEN_RECT_WIDTH - 56, 58))
        smsBtn2.setImage(UIImage.init(named: "login"), for: .normal)
        smsBtn2.imageView?.contentMode = .scaleAspectFit
        smsBtn2.isUserInteractionEnabled = false

        //输入框 邀请码
        textField = UITextField.init(frame: CGRectMake((SCREEN_RECT_WIDTH - 200)/2.0, SCREEN_RECT_HEIGHT - uiModel.logBtnOffsetY - 120, 200, 50))
        textField.background = UIImage.init(named: "input_bg")!
        textField.placeholder = "请输入邀请码（非必填）"
        textField.font = .boldSystemFont(ofSize: 16)
        textField.textColor = UIColor.init(red: 86/255.0, green: 64/255.0, blue: 56/255.0, alpha: 1.0)
        textField.textAlignment = .center
        textField.tintColor = UIColor.init(red: 86/255.0, green: 64/255.0, blue: 56/255.0, alpha: 1.0)
        textField.returnKeyType = .done
        textField.delegate = self

        //协议复选框
        uiModel.checkedImg = UIImage.init(named: "agree_sel")!
        uiModel.uncheckedImg = UIImage.init(named: "agree_unsel")!
        uiModel.checkBoxWH = 24.0
        uiModel.checkboxOffsetX = 16.0
        uiModel.checkboxOffsetY_B = SCREEN_RECT_HEIGHT - 524 as NSNumber
        uiModel.privacyState = false

        //协议设置
        let pryStr = "我已认真阅读并同意\(appName)《使用协议》、《隐私政策》和&&默认&&"
        let style = NSMutableParagraphStyle.init()
        style.lineSpacing = 2
        let strappPrivacy = NSAttributedString.init(string: pryStr,attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.black,NSAttributedString.Key.paragraphStyle:style])
        let str1 = NSAttributedString.init(string: "《使用协议》",attributes: [NSAttributedString.Key.link:link1])
        let str2 = NSAttributedString.init(string: "《隐私政策》",attributes: [NSAttributedString.Key.link:link2])
        uiModel.privacySymbol = true

        uiModel.appPrivacyDemo = strappPrivacy
        uiModel.appPrivacy = [str1,str2]
        uiModel.privacyColor = UIColor.init(red: 165/255.0, green: 0, blue: 0, alpha: 1.0)
        uiModel.privacyLabelOffsetY = SCREEN_RECT_HEIGHT - 536
        uiModel.appPrivacyOriginLR = [40,30]

        //底部其他登录方式设置
        uiModel.ifCreateCustomView = true
        let frame = CGRectMake(0, SCREEN_RECT_HEIGHT - 200, SCREEN_RECT_WIDTH, 200);

        uiModel.customOtherLoginViews = [textField,smsBtn2,smsBtn,setThirdViewWithframe(frame: frame,appName:appName)]

        /*web协议页面导航*/
        uiModel.webNavReturnImg = UIImage.init(named: "close")!
        uiModel.webNavColor = UIColor.white
        uiModel.webNavTitleAttrs = [NSAttributedString.Key.foregroundColor:UIColor.black, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16),]

        //****想登录按钮始终可点击 就用下面方法，可在未勾选隐私协议的时候进行二次弹窗，确认后继续登录
        /**忽略隐私条款check框状态，登陆按钮一直可点击 默认:NO(不忽略) */
        uiModel.ignorePrivacyState = true;
        //当忽略隐私条款check框状态，登陆按钮一直可点击时，不需要抖动提示
        if (uiModel.ignorePrivacyState) {
            uiModel.privacyUncheckAnimation = false;
            TXLoginOauthSDK.setLoginDelegate(lvc)
        } else {
            //未勾选隐私条款
            uiModel.checkTipText = "请同意并阅读协议"
        }

        /**登录页面出现模式设置*/
        uiModel.authWindow = false
        uiModel.edgeWindow = false
        uiModel.faceOrientation = false
        uiModel.appLanguageType = AuthLanguageType.simplifiedChinese

    }

    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

    //其他登录方式view
    func setThirdViewWithframe(frame:CGRect,appName:String) -> UIView {
        let otherView = UIView.init(frame: frame)
        otherView.backgroundColor = .clear

        //        let line1 = UILabel.init(frame: CGRectMake(30, 15, (otherView.frame.size.width-160)/2.0, 1))
        //        line1.backgroundColor = .black
        //
        //        let line2 = UILabel.init(frame: CGRectMake(otherView.frame.size.width - ((otherView.frame.size.width - 160)/2.0) - 30, 15, (otherView.frame.size.width-160)/2.0, 1))
        //        line2.backgroundColor = .black
        //
        //        otherView.addSubview(line1)
        //        otherView.addSubview(line2)
        //
        //        let titleLabel = UILabel.init(frame: CGRectMake((otherView.frame.size.width-100)/2.0, 0, 100, 30))
        //        titleLabel.backgroundColor = .clear
        //        titleLabel.font = .systemFont(ofSize: 12)
        //        titleLabel.textColor = .black
        //        titleLabel.textAlignment = .center
        //        titleLabel.text = "其他登录方式"
        //        otherView.addSubview(titleLabel)

        //        let btn = UIButton.init(frame: CGRectMake((otherView.frame.size.width - 44)/2.0, 50, 44, 44))
        //        btn.setImage(UIImage.init(named: "sms_login"), for: .normal)
        //        btn.imageView?.contentMode = .scaleAspectFill
        //        btn.addTarget(self, action: #selector(smsLogin), for: .touchUpInside)
        //        otherView.addSubview(btn)
        //
        //        let smsLabel = UILabel.init(frame: CGRectMake((otherView.frame.size.width - 120)/2.0, 94, 120, 30))
        //        smsLabel.backgroundColor = .clear
        //        smsLabel.font = .systemFont(ofSize: 11)
        //        smsLabel.textColor = .black
        //        smsLabel.textAlignment = .center
        //        smsLabel.text = "短信验证码登录"
        //        otherView.addSubview(smsLabel)

        //tips
        let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()

        let tips1 = NSAttributedString.init(string: "未注册过的用户将直接为您创建", attributes: [ NSAttributedString.Key.foregroundColor : UIColor.black , NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10)])
        let tips2 = NSAttributedString.init(string: appName, attributes: [NSAttributedString.Key.foregroundColor : UIColor.init(red: 165/255.0, green: 0, blue: 0, alpha: 1.0) , NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10)])
        let tips3 = NSAttributedString.init(string: "用户", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black , NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10)])
        attributedStrM.append(tips1)
        attributedStrM.append(tips2)
        attributedStrM.append(tips3)


        let tipsLabel = UILabel.init(frame: CGRectMake(20, 148, otherView.frame.size.width - 40, 30))
        tipsLabel.textAlignment = .center
        tipsLabel.attributedText = attributedStrM
        otherView.addSubview(tipsLabel)

        return otherView
    }
    //切换短信登录
    @objc func smsLogin() {
        let vc = UIApplication.shared.keyWindow?.rootViewController
        vc?.dismiss(animated: true)
        TXLoginOauthSDK.preLogin { dict in
        } fail: { error in
        }
        changeSmsLoginView()
    }

    func changeSmsLoginView(){
        RuhunVerifyPlugin.channel.invokeMethod("changeSmsLogin", arguments: "")
    }

    //顶部view
    func setTopNavViewWithFrame(frame:CGRect) -> UIView {
        let navBackView = UIView.init(frame: frame)
        navBackView.backgroundColor = .clear
        let status = UIApplication.shared.statusBarFrame.size.height

        let titleLabel = UILabel.init(frame: CGRectMake(65, status, navBackView.frame.size.width - 130, 44))
        titleLabel.backgroundColor = .clear
        titleLabel.font = .boldSystemFont(ofSize: 22)
        titleLabel.textColor = .black
        titleLabel.textAlignment = .center
        titleLabel.text = "欢迎登录"
        navBackView.addSubview(titleLabel)

        let btn = UIButton.init(frame: CGRectMake(navBackView.frame.size.width - 60, status, 44, 44))
        btn.setImage(UIImage.init(named: "close"), for: .normal)
        btn.imageView?.contentMode = .scaleAspectFill
        btn.addTarget(self, action: #selector(backClick), for: .touchUpInside)
        navBackView.addSubview(btn)

        return navBackView
    }

    //关闭授权页面
    @objc func backClick() {
        RuhunVerifyPlugin.channel.invokeMethod("authViewDispose", arguments: "")
        TXLoginOauthSDK.delectScrip()
        let vc = UIApplication.shared.keyWindow?.rootViewController
        vc?.dismiss(animated: true)
        TXLoginOauthSDK.preLogin { dict in
        } fail: { error in
        }
    }
}
